import 'package:craze/common/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'dart:io';

class ScanView extends StatefulWidget {
  const ScanView({super.key});

  @override
  State<ScanView> createState() => _ScanViewState();
}

class _ScanViewState extends State<ScanView> {
  File? _selectedImage;
  final TextEditingController _questionController = TextEditingController();

  // 选择图片
  Future<void> _pickImage() async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final File? file = await result.first.file;
      if (file != null) {
        setState(() {
          _selectedImage = file;
        });
      }
    }
  }

  // 拍摄图片
  // Future<void> _takePhoto() async {
  //   final AssetEntity? entity = await CameraPicker.pickFromCamera(
  //     context,
  //     pickerConfig: CameraPickerConfig(enableRecording: false),
  //   );

  //   if (entity != null) {
  //     final File? file = await entity.file;
  //     if (file != null) {
  //       setState(() {
  //         _selectedImage = file;
  //       });
  //     }
  //   }
  // }

  // 显示选择菜单
  void _showImageSourceOptions() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SafeArea(
          child: Wrap(
            children: <Widget>[
              ListTile(
                leading: const Icon(Icons.photo_library),
                title: const Text('Choose from album'),
                onTap: () {
                  Navigator.of(context).pop();
                  _pickImage();
                },
              ),
              // ListTile(
              //   leading: const Icon(Icons.camera_alt),
              //   title: const Text('Take a photo'),
              //   onTap: () {
              //     Navigator.of(context).pop();
              //     _takePhoto();
              //   },
              // ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: 1.sw,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            child: Column(
              children: [
                Row(
                  children: [
                    GestureDetector(
                      onTap: () {
                        GoRouter.of(context).pop();
                      },
                      child: Icon(
                        MyIcons.iconBack,
                        size: 24,
                        color: Colors.white,
                      ),
                    ),

                    Expanded(
                      child: Center(
                        child: Text(
                          'Ai species identification',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 22.sp,
                            fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                            fontWeight: FontWeight.w400,
                            height: 1.36,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),

                SizedBox(height: 32.h),

                Text(
                  'You can upload photos of marine life to get information about marine life.',
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontFamily: GoogleFonts.inter().fontFamily,
                    fontWeight: FontWeight.w400,
                    height: 1.38,
                  ),
                ),

                SizedBox(height: 70.h),

                // 图片选择
                GestureDetector(
                  onTap: _showImageSourceOptions,
                  child: Container(
                    width: 216.w,
                    height: 216.w,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image:
                            _selectedImage != null
                                ? FileImage(_selectedImage!) as ImageProvider
                                : AssetImage(MyImages.scan),
                        fit: BoxFit.cover,
                      ),
                      borderRadius:
                          _selectedImage != null
                              ? BorderRadius.circular(10.r)
                              : BorderRadius.circular(0.r),
                    ),
                  ),
                ),

                SizedBox(height: 70.h),

                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    'Input Problem',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                      fontWeight: FontWeight.w400,
                      height: 1.38,
                    ),
                  ),
                ),

                SizedBox(height: 13.h),

                // 问题输入框
                Container(
                  height: 52.h,
                  alignment: Alignment.centerLeft,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment(0.50, 0.00),
                      end: Alignment(0.50, 0.86),
                      colors: [
                        Color(0xFF0076FF).withAlpha(60),
                        Color(0xFF045EC6).withAlpha(60),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(10.r),
                    border: Border.all(color: MyColors.blue, width: 1.w),
                  ),
                  child: TextField(
                    controller: _questionController,
                    style: TextStyle(color: Colors.white, fontSize: 14.sp),
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: 'Please input your question...',
                      hintStyle: TextStyle(
                        color: Colors.white.withAlpha(128),
                        fontSize: 14.sp,
                      ),
                    ),
                  ),
                ),

                const Spacer(),

                GestureDetector(
                  onTap: () {
                    // 上传图片和问题的逻辑
                    if (_selectedImage == null) {
                      MyToast.showWarning(
                        context,
                        'Please select or take a photo',
                      );
                      return;
                    }

                    // 使用GoRouter导航到AI结果页面
                    GoRouter.of(context).pushNamed(
                      'aiResult',
                      extra: {
                        'imageFile': _selectedImage,
                        'question':
                            _questionController.text.isEmpty
                                ? 'Please identify this marine life, reply in English'
                                : _questionController.text,
                      },
                    );
                  },
                  child: Container(
                    width: double.infinity,
                    height: 52.h,
                    decoration: ShapeDecoration(
                      gradient: LinearGradient(
                        begin: Alignment(0.50, 0.00),
                        end: Alignment(0.50, 0.86),
                        colors: [
                          const Color(0xFF0076FF),
                          const Color(0xFF045EC6),
                        ],
                      ),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30.r),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        'Upload',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.sp,
                          fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  ),
                ),

                SizedBox(height: 16.h),

                Text(
                  'Please upload images under 5MB',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14.sp,
                    fontFamily: GoogleFonts.inter().fontFamily,
                    fontWeight: FontWeight.w400,
                    height: 1.50,
                  ),
                ),

                SizedBox(height: 16.h),

                // Eula
                GestureDetector(
                  onTap: () {
                    WangYe.openUrl(
                      'https://www.freeprivacypolicy.com/live/d6a9a407-9d63-42af-9bc0-471389957c78',
                    );
                  },
                  child: Align(
                    alignment: Alignment.center,
                    child: Text(
                      'EULA',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontFamily: GoogleFonts.inter().fontFamily,
                        fontWeight: FontWeight.w400,
                        decoration: TextDecoration.underline,
                      ),
                    ),
                  ),
                ),

                const Spacer(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
